<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 15:34
 */

namespace App\Http\Controllers\Home;

use App\Model\Address;
use App\Model\GoodsSpecsName;
use App\Model\GoodsSpecsVal;
use App\Model\PurchaseOrder;
use App\Model\RecordTransaction;
use App\Model\Replenish;
use App\Model\ShopGoods;
use App\Model\ShopGoodsClassify;
use App\Model\ShopGoodsImg;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use App\Model\StoreGoodsSet;
use App\Model\StoresCenter;
use App\Model\StoresCenterGoods;
use App\Model\StoresProfitRecord;
use App\Model\Members;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class StoresCenterController extends BaseController
{
    /**
     * 门店中心
     */
    public function CenterIndex() {
        $user = session('home_user');
        $StoresCenterModel = new StoresCenter();
        $Stores = $StoresCenterModel->where(['uid' => $user->uid ])->first();
        if($Stores) {
            if ( $Stores["type"] == 1 ) {
                return view('Home.stores.stores_index');
            } else {
                return redirect( '/home/member/index' );
            }
             return view('Home.stores.stores_index');       
        } else {
            return view('Home.stores.stores_center');
        }
    }

    /**
     * 门店中心处理
     * @param Request $request
     * @return array
     */
    public function Stores(Request $request)
    {
        $data = $request->all();
        $StoresCenterModel = new StoresCenter();
        $UserModel = new Members();
        $orderModel = new ShopOrder();
        $user = session('home_user');
        $uid = $user->uid;
        switch ($data['class']){
            case 'select': //查询
                $rico = $StoresCenterModel->where(['uid' => $uid])->first();
                $rico["apply_time"] = date( "Y-m-d H:i:s", $rico["apply_time"] );
                $rico["audit_time"] = date( "Y-m-d H:i:s", $rico["audit_time"] );
                if ($rico) {
                    return ['code'=>1,'data'=>$rico];
                } else {
                    return ['code'=>0,'data'=>'没有数据'];
                }
                break;
            case 'deliver': //门店确认发货
                $deliver['status'] = 2;
                $deliver['couriertime'] = time();
                $deliver['expressage'] = $data['expressage'];
                $deliver['courier_number'] = $data['courier_number'];
                $deliver['remark'] = $data['remark'];
                $rico = ShopOrder::where('id',$data['id'])->update( $deliver );
                if($rico){
                    return ['code' => 1, 'data' => '发货成功'];
                } else {
                    return ['code' => 0, 'data' => '发货失败'];
                }
                break;
            case 'inventory': //我的库存
               $stores_number = $StoresCenterModel->where( [ 'uid' => $uid ] )->value("number");
               $inventory = StoresCenterGoods::where( [ 'stores_sn' => $stores_number ] )->select('goodsname', 'inventory', 'sold' ,'specs_txt')->get()->toArray();
               foreach ( $inventory as $key => $value ){
                if ( !is_null($value['specs_txt']) ){
                    $specs = explode('|',$value['specs_txt']);//库存改为数组形式
                    foreach ( $specs as $k => $v ) {
                        $str = substr($v, 0, strrpos($v, "--"));
                        $str = substr($str, 1, -1);
                        $specs[$k] = array_filter(explode(';', $str));
                        foreach ( $specs[$k] as $kk => $vv ){
                            $array[$key][$k]['specs'][$kk] =  substr($vv,strripos($vv,":")+1);
                        }
                        //数量
                        $str2 = strstr($v,'--');
                        $number = substr($str2,2);
                        $array[$key][$k]['number'] = $number;
                    }
                    $specs = $array[$key];
                    $inventory[$key]['specs_txt'] = $specs;
                }
            }
                if ( $inventory ) {
                    return ['code' => 1, 'data' => $inventory ];
                } else {
                    return ['code' => 0, 'data' => '暂无数据'];
                }
                break;
            case 'lanLong': //查出该门店的经纬度
                $lanLong = StoresCenter::where( [ 'number' => $data['number'] ] )->select( 'type', 'latitude' )->first();
                if ( $lanLong ) {
                    if ( $lanLong['type'] == 1 ) {
                        return ['code' => 1, 'data' => $lanLong ];
                    } else {
                        return ['code' => 0, 'data' => '该门店不存在!' ];
                    } 
                } else {
                    return ['code' => 0, 'data' => '该门店不存在!' ];
                }
                break;
            case 'stores_finds':
                if ( $data['store_keyword'] == "" ) {
                    return ['code' => 0, 'data' => '请输入门店关键字'];
                }
                $StoreNumberData = StoresCenter::where('shop_name','like','%'.$data['store_keyword'].'%')
                                ->orWhere('name','like','%'.$data['store_keyword'].'%')
                                ->orWhere('phone','like','%'.$data['store_keyword'].'%')
                                ->orWhere('province','like','%'.$data['store_keyword'].'%')
                                ->orWhere('city','like','%'.$data['store_keyword'].'%')
                                ->orWhere('district','like','%'.$data['store_keyword'].'%')
                                ->select( "number", "type" )
                                ->get()
                                ->toArray();
                foreach ($StoreNumberData as $k => $v) {
                    if ( $v['type'] != 1 ) {
                        unset( $StoreNumberData[$k] );           
                    }              
                }                
                if ( $StoreNumberData ) 
                {
                    return ['code' => 1, 'data' => $StoreNumberData ];            
                } else {
                    return ['code' => 0, 'data' => '暂未搜索到你想要的门店,试试自己填写吧']; 
                }                
                break;
            case 'add':
                $Stores = $StoresCenterModel->where(['uid' => $user->uid])->count();
                if($Stores){
                    return ['code'=>0,'data'=>'已申请'];
                }

                $latitude = explode(",",$data['stores']['latitude']);
                $data['stores']['uid'] = $uid;
                $data['stores']['apply_time'] = time();
//                dump($data['stores']);exit;
                $rico = $StoresCenterModel->add($data['stores']);
                if ($rico) {
                    return ['code'=>1,'data'=>'申请成功'];
                } else {
                    return ['code'=>0,'data'=>'申请失败'];
                }
                break;

            case 'stores_is_far':
                $latitude = $data['latitude'];
                $UserLati = explode( ",", $latitude );
                $userLongitude = $UserLati[0]; 
                $userLatitude = $UserLati[1];
                //查出数据库所有门店的经纬度
                $AllLatitudes = StoresCenter::where( [ 'type' => 1 ] )->select("latitude")->get()->toArray();
                foreach ($AllLatitudes as $k => $v) {
                    $StoreLati = explode( ",", $v["latitude"] );
                    $storeLongitude = $StoreLati[0]; 
                    $storeLatitude = $StoreLati[1];
                    $isfarStore = GETDISTANCE( $userLongitude, $userLatitude, $storeLongitude, $storeLatitude, 2, 2 );
                    if ( $isfarStore <= 3 ) {
                        return ['code' => 1, 'data' => '该地址3公里内已有门店存在！'];exit;
                    }
                }
                break;

            case 'friends': //门店伙伴
                $Stores = $StoresCenterModel->where( [ 'uid' => $user->uid ] )->first();
                $friendsData = ShopOrder::where( 'stores_number', $Stores["number"] )->whereNotIn( 'uid', [ $uid ] )->select( 'uid', 'ordersn', 'paytime', 'ordertype', 'price')->groupBy('uid')->orderBy('paytime','desc')->paginate(5);
                foreach ($friendsData as $k => $v) {
                    $v["paytime"] = date( "Y-m-d H:i:s", $v["paytime"] );
                    switch ( $v["ordertype"] ) {
                        case 1:
                            $v["ordertype"] = "直商城";
                            break;
                        case 2:
                            $v["ordertype"] = "微商城";
                            break;
                        case 3:
                            $v["ordertype"] = "超级商城";
                            break;                       
                    }
                    $v["uid"] = Members::where( ['uid' => $v["uid"] ] )->value('user_name');
                }
                if ( $friendsData ) {
                    return [ 'code' => 1, 'data' => $friendsData ];
                } else {
                    return [ 'code' => 0, 'data' => '' ];
                }
                break;
            case 'first':
                //查询该门店是否存在
                $Stores = $StoresCenterModel->where(['uid' => $user->uid])->first();
                if (!$Stores ) {
                    return ['code'=>0,'data'=>'提交申请'];
                }
                //该门店订单总数
                $rico = $orderModel->where([ 'stores_number' => $Stores["number"] ])->count();
                //门店收益总数
                $profit = StoresProfitRecord::where([ 'store_number' => $Stores["number"] ])->count();
                //补货单数
                $replenish = Replenish::where(['stores_num' => $Stores["number"],'is_cancel' => 1])->count();
                //进货单数
                $purchase = PurchaseOrder::where(['stores_num' => $Stores["number"],'is_cancel' => 1])->count();
                //我的库存总数
                $inventory = StoresCenterGoods::where([ 'stores_sn' => $Stores["number"] ])->where('inventory','>',0)->sum('inventory');
                //门店伙伴个数
                $friendsCounts = count( ShopOrder::where( 'stores_number', $Stores["number"] )->whereNotIn( 'uid', [ $uid ] )->select( 'uid')->groupBy('uid')->get()->toArray() );
                return ['code'=>1,
                    'data'=>$Stores,
                    'rico' => $rico,
                    'profit' => $profit,
                    'inventory' => $inventory,
                    'friendsCounts' => $friendsCounts,
                    'purchase' =>$purchase ,
                    'replenish' => $replenish
                ];
                break;
            case 'near_stores': //查询附近门店
                $latitude = $data['latitude'];
                $UserLati = explode( ",", $latitude );
                $userLongitude = $UserLati[0]; 
                $userLatitude = $UserLati[1];
                //查出数据库所有门店的经纬度
                $AllLatitudes = StoresCenter::where( [ 'type' => 1 ] )->select( "shop_name", "latitude" )->get()->toArray();
                $StoresNearby = [];
                foreach ($AllLatitudes as $k => $v) {
                    $StoreLati = explode( ",", $v["latitude"] );
                    $storeLongitude = $StoreLati[0]; 
                    $storeLatitude = $StoreLati[1];
                    $isfarStore = GETDISTANCE( $userLongitude, $userLatitude, $storeLongitude, $storeLatitude, 2, 2 );
                    if ( $isfarStore <= 5 ) {
                       $StoresNearby[$k] = [ "shop_name"=> $v["shop_name"], "far"=> $isfarStore ];
                    }
                }
                //通过冒泡排序使门店按照距离由小到大的排序
                if ( count( $StoresNearby ) >0 ) {
                    for ( $j = 0; $j < count( $StoresNearby )-1; $j++ ) {
                        //该层循环用来控制每轮 冒出一个数 需要比较的次数 
                        for ( $m = 0; $m < count( $StoresNearby )-1-$j; $m++ ) { 
                            $k = $m+1;
                            if ( !empty( $StoresNearby[$m] ) && !empty( $StoresNearby[$k] ) ) {
                               if ( $StoresNearby[$m]["far"] > $StoresNearby[$k]["far"] ) {
                                    $t = $StoresNearby[$m];
                                    $StoresNearby[$m] = $StoresNearby[$k];
                                    $StoresNearby[$k] = $t;
                                }
                            } 
                        }
                    }
                }
                //查询该用户是否已绑定门店
                $isBindNumber = Members::where( [ 'uid' => $uid ] )->value('stores_number');
                if ( $isBindNumber != '0' ) {
                    $isBind = 1;
                } else {
                    $isBind = 0;
                }
                if ( $StoresNearby ) {
                    return [ 'code' => 1, 'data' => $StoresNearby, 'is_bind' => $isBind ];
                } else {
                    return ['code'=>0,'data'=>'', 'is_bind' => $isBind ];
                }
                break;
        }
    }

    /**
     * 门店订单
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function StoresOrder()
    {
        return view('Home.stores.order');
    }
    /**
     * 门店收益
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|\think\response\View
     */
    public function StoresRecord()
    {
        return view('Home.stores.record');
    }

      /**
     * 订单详情
     */
    public function orderComment()
    {
        return view('Home.stores.ordercomment');
    }

     /**
     * 确认发货页
     */
    public function deliver()
    {
        return view('Home.stores.deliver');
    }


    /**
     * 门店收益页
     */
    public function record()
    {
        return view('Home.stores.record');
    }

     /**
     * 我的库存页
     */
    public function inventory()
    {
        return view('Home.stores.inventory');
    }


    /**
     * 我的门店页
     */
    public function mystore()
    {
        return view('Home.stores.mystore');
    }


      /**
     * 门店伙伴
     */
    public function friends()
    {
        return view('Home.stores.friends');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 我要进货
     */
    public function purchase()
    {
        return view('Home.stores.purchase');
    }

    /**
     * @param Request $request
     * @return array
     * 进货订单
     */
    public function getPurchase( Request $request )
    {
        $data = $request->all();
        $user = session('home_user');
        $StoresCenterModel = new StoresCenter();
        $StoresCenterGoodsModel = new StoresCenterGoods();
        $AddressModel = new Address();
        $membersModel = new Members();
        $GoodsModel = new ShopGoods();
        $storeGoodsAllId = [];
        $storeGoodsId = [];
        $stores_id = $StoresCenterModel->where(['uid'=>$user->uid])->value('id');
        $StoresNumber = $StoresCenterModel->where( [ 'id' => $stores_id ] )->value( 'number' );
        $storeGoodsData = StoresCenterGoods::where( [ 'stores_id' => $stores_id ] )->select( 'gid' )->get()->toArray();
        foreach ($storeGoodsData as $key => $value) {
            array_push( $storeGoodsId, $value['gid'] );
        }
        $table = ShopGoodsClassify::where(['type'=>2])->select('id');
        $classify = $table->get()->toArray();
        $pid = [];
        if (!empty($classify)) {
            foreach ($classify as $value) {
                $pid[] = $value['id'];
            }
        } else {
            return ['code'=>0,'data'=>'暂时还没有商品'];
        }
        $goods = $GoodsModel->where( [ 'type' => 1, 'status' =>1 ] )->whereIn( 'cid', $pid )->select( 'id', 'goodsname' )->get()->toArray();
        foreach ($goods as $k => $v) {
            array_push( $storeGoodsAllId, [ 'gid' => $v['id'], 'goodsname' => $v['goodsname'] ] );
        }
        foreach ($storeGoodsAllId as $k => $v) {
            $goodsIdExist = in_array( $v['gid'], $storeGoodsId );
            if ( !$goodsIdExist ) {
                $goodsDatas['gid'] = $v['gid'];
                $goodsDatas['stores_id'] = $stores_id;
                $goodsDatas['stores_sn'] = $StoresNumber;
                $goodsDatas['goodsname'] = $v['goodsname'];
                $goodsDatas['inventory'] = 0;
                $goodsDatas['sold'] = 0;
                $goodsDatas['time'] = time();
                $specsName = GoodsSpecsName::where('goods_id',$v['gid'])->select('id','name')->get()->toArray();
                if ( $specsName ){
                    $num = count($specsName);
                    foreach ( $specsName as $key => $value ){
                        $value = GoodsSpecsVal::where('specs_id',$value['id'])->pluck('val')->toArray();
                        $specsData = getCombinationToString($value,$num);
                    }
                    foreach ( $specsData as $kk => $vv){
                        $specsData[$kk] = array();
                        $specsData[$kk]['specs'] = $vv;
                        $specsData[$kk]['number'] = 0;
                    }
                    $specsName = GoodsSpecsName::where('goods_id',$v['gid'])->get()->toArray();
                    foreach ( $specsData as $key => $value ){
                        $arr = array();
                        $arr = explode('_',$value['specs']);
                        $specsList = '';
                        for ($i = 0;$i<count($specsName);$i++){
                            $specsList .= $specsName[$i]['name'].':'.$arr[$i].';';
                        }
                        $specs[$key] ='['.$specsList.']--'.$value['number'];
                    }
                    $specsTxt = implode('|',$specs);
                    $goodsDatas['specs_txt'] = $specsTxt;
                } else {
                    $goodsDatas['specs_txt'] = null;
                }
                $storeGoodsDataAdd = $StoresCenterGoodsModel->insert( $goodsDatas );
            }
        }
        switch ( $data['class'] ){
            case 'select'://查询库存商品名称,总数及规格
                $storesId = $StoresCenterModel->where(['uid'=>$user->uid])->value('id');
                $goods = $StoresCenterGoodsModel->where(['stores_id'=>$storesId])->get()->toArray();
                if ( $goods ){
                    $arr = array();
                    foreach ( $goods as $key => $value ){
                        $specsName[$key] = GoodsSpecsName::where(['goods_id' => $value['gid']])->get()->toArray();
                        if ( $specsName[$key] ){
                            foreach ( $specsName[$key] as $k => $v ){
                                $specsVal[$k] = GoodsSpecsVal::select('val')->where(['specs_id' => $v['id']])->get()->toArray();
                                if ( $specsVal[$k] ){
                                    $val = array();
                                    foreach ( $specsVal[$k] as $vv ){
                                        array_push($val,$vv['val']);
                                    }
                                    $arr[$key][$v['name']] = $val;
                                }
                                $goods[$key]['specs'] = $arr[$key];
                            }
                        }
                    }
                    return ['code' => 1,'data' =>$goods];

                } else {
                    return ['code' => 0,'data' => '暂无数据'];
                }
                break;
            case 'purchase'://生成进货订单
                $ordersn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                //门店
                $address = $AddressModel->get_address($user->uid);
                if (!$address){
                    return ['code' => 0,'data' =>'请先添加收货地址'];
                }
                $Store = $StoresCenterModel->where(['uid' => $user->uid])->first();
                $goods = ShopGoods::where(['id' => $data['order']['gid']])->first();
                if ( !is_numeric($data['order']['specs_txt'])){
                    $specs = $data['order']['specs_txt'];
                    $patterns = "/\d+/";
                    preg_match_all($patterns,$specs,$numData);
                    $totalNum = array_sum( $numData[0]);
                } else {
                    $specs = null;
                    $totalNum = $data['order']['specs_txt'];
                }
                $order = [
                    'ordersn' => $ordersn,
                    'stores_num' => $Store['number'],
                    'goods_name' => $goods['goodsname'],
                    'price' => $goods['memberprice'],
                    'total_price' => $goods['memberprice'] * $totalNum,
                    'total_quantity' => $totalNum,
                    'stores_name' => $Store['shop_name'],
                    'name' => $user->user_name,
                    'is_self' => $data['pick_self'],
                    'status' => 0,
                    'specs_txt' => $specs,
                    'created_at' => date('Y-m-d H:i:s',time())
                ];
                $res = PurchaseOrder::create($order);
                $orderId = PurchaseOrder::where(['ordersn' => $ordersn])->value('id');
                if ( $res ){
                    return ['code' => 1,'data'=>$orderId];
                } else {
                    return ['code' => 0,'data'=>'参数错误'];
                }
                break;
            case 'find'://查找订单
                //获取用户信息
                $member = $membersModel->find_members(['uid' => $user->uid],['credit1','credit2','credit3','credit4','voucher','credit5','level','stores_number']);
                //获取默认收货地址
                $address = $AddressModel->get_address($user->uid);
                if (!$address){
                    return ['code' => 0,'data' =>'请先添加收货地址'];
                }
                $order = PurchaseOrder::where(['id' => $data['id']])->first();
                $goods = ShopGoods::where(['goodsname' => $order['goods_name']])->first();
                //根据收货地址计算运费
                $weight = ceil($goods['weight'] * $order['total_quantity']);
                if ( $order['is_self'] == 1 ){
                    $order->postage = 0;
                } else {
                    $order->postage = $this->getPostage( $weight ,$address['province']);
                }
                $order->save();
                //商品封面图
                $order['img'] = ShopGoodsImg::where(['gid' => $goods['id']])->value('img');
                //订单总价(包含运费)
                $order['total'] = $order['total_price'] + $order['postage'];
                $money = FIGURE( $member['credit1'],$member['credit2'],$member['credit4'],$member['voucher'],$order['total']);
                $data = [
                    'order' => $order,
                    'address' => $address,
                    'money' => $money
                ];
                if ( $data ){
                    return ['code' => 1,'data' => $data];
                } else {
                    return ['code' => 0,'data' => '订单不存在'];
                }
                break;
            case 'pay'://支付订单
                $member = $membersModel->find_members(['uid' => $user->uid],['credit1','credit2','credit3','credit4','voucher','credit5','level','stores_number']);
                //获取收货地址
                $address = Address::where(['id' => $data['addressId']])->first();
                //获取订单
                $order = PurchaseOrder::where(['id'=>$data['id']])->first();
                //启动事务
                DB::beginTransaction();
                try{
                    //扣款
                    $money = [
                        'credit1' => $member->credit1 - $data['money']['data']['credit1'],
                        'credit2' => $member->credit2 - $data['money']['data']['credit2'],
                        'credit4' => $member->credit4 - $data['money']['data']['credit4'],
                        'voucher' => $member->voucher - $data['money']['data']['voucher']
                        ];
                    Members::where(['uid' => $user->uid])->update($money);
                    //修改订单状态
                    $order->address = $address['province'].$address['city'].$address['district'].$address['address'];
                    $order->consignee = $address['name'];
                    $order->phone = $address['phone'];
                    $order->status = 1;
                    $order->paytime = date('Y-m-d H:i:s',time());
                    $order->save();
                    //生成交易记录
                    $totalMoney = array_sum($data['money']['data']);
                    $transaction = [
                        'uid' => $user->uid,
                        'ordersn' => $order['ordersn'],
                        'money' => -$totalMoney,
                        'type' => 6,
                        'time' => time(),
                        'explain' => '门店进货',
                        'remark' => '电子币 : '.-$data['money']['data']['credit1'].' , 奖励币 : '.-$data['money']['data']['credit2'].' , 积分 : '.-$data['money']['data']['credit4'].' , 代金券 : '.-$data['money']['data']['voucher']
                    ];
                    RecordTransaction::create($transaction);
                    //提交事物
                    DB::commit();
                }catch (\Exception $exception){
                    //回滚
                    DB::rollBack();
                    return ['code' => 0 ,'data' =>'支付失败'];
                }
                return ['code' => 1 ,'data' =>'支付成功'];
                break;

        }

    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 订单支付页面
     */

    public function orderPage()
    {
        return view('Home.stores.orderpage');
    }

    public function purchaseDetail()
    {
        return view('Home.stores.purchasedetail');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 进货记录
     */
    public function purchaseRecord()
    {
        return view('Home.stores.purchaserecord');
    }
    //进货记录
    public function getPurchaseRecord( Request $request)
    {
        $data = $request->all();
        $user = session('home_user');
        $orders = PurchaseOrder::where(['is_cancel' => 1])->get()->toArray();

        foreach ( $orders as $value ){
            if(time()-strtotime($value['created_at']) > 6 * 60 * 60 && $value['status'] == 0){//订单超过6小时自动取消
                PurchaseOrder::where('id',$value['id'])->update(['is_cancel'=>-1]);
            }
        }
        switch ($data['class']){
            case 'select'://查询门店所有进货记录
                $stores_num = StoresCenter::where(['uid' => $user->uid])->value('number');//获取门店号
                $orders = PurchaseOrder::where(['is_cancel' => 1,'stores_num' => $stores_num])->orderBy('id','desc')->paginate(5);
                foreach ( $orders as $key => $value ){
                    $goods = ShopGoods::where(['goodsname' => $value['goods_name']])->first();
                    $img = ShopGoodsImg::where(['gid' => $goods['id']])->value('img');
                    $orders[$key]['img'] = $img;
                    $orders[$key]['total'] = $value['total_price'] + $value['postage'];
                }
                if ( $orders ){
                    return ['code' => 1 ,'data' => $orders];
                } else {
                    return ['code' => 0 ,'data' => '暂无进货记录'];
                }
                break;
            case 'detail':
                $order = PurchaseOrder::where(['id' => $data['id']])->first();
                $goods = ShopGoods::where(['goodsname' => $order['goods_name']])->first();
                //商品封面图
                $order['img'] = ShopGoodsImg::where(['gid' => $goods['id']])->value('img');
                //订单总价(包含运费)
                $order['total'] = $order['total_price'] + $order['postage'];
                if ( $order ){
                    return ['code' => 1 ,'data' => $order];
                } else {
                    return ['code' => 0 ,'data' =>'参数错误'];
                }
                break;
            case 'confirm'://确认收货
                $stores_num = StoresCenter::where(['uid' => $user->uid])->value('number');//获取门店号
                $order = PurchaseOrder::where(['id' => $data['id']])->first();
                //获取门店
                $store = StoresCenter::where(['uid' => $user->uid])->first();
                //确认收货后增加门店订金
                DB::beginTransaction();
                $store->earnest_money = $store->earnest_money + $order['total_price'];
                $store->save();
                //更改订单状态
                $order->status = 3;
                $res = $order->save();
                if ( !$res ){
                    DB::rollback();
                    return ['code' => 0,'data' =>'进货失败'];
                }
                //查询商品库存并增加
                $goods = StoresCenterGoods::where(['goodsname' => $order['goods_name'],'stores_sn' => $stores_num])->first();
                $inventoryBefore = $goods->inventory;
                if (is_null($goods['specs_txt'])){
                    $inventoryAfter = $goods->inventory = $goods->inventory + $order['total_quantity'];
                    $re = $goods->save();
                } else {
                    $specs = explode('|',$goods['specs_txt']);//库存改为数组形式
                    foreach ( $specs as $key => $value ) {
                        $str = substr($value, 0, strrpos($value, "--"));
                        $str = substr($str, 1, -1);
                        $specs[$key] = array_filter(explode(';', $str));
                        foreach ( $specs[$key] as $kk => $vv ){
                            $array[$key]['specs'][] =  substr($vv,strripos($vv,":")+1);
                        }
                        $array[$key]['revise'] = 0;
                           //数量
                           $str2 = strstr($value,'--');
                           $number = substr($str2,2);
                           $array[$key]['number'] = $number;
                    }
                    $specs = $array;
                    $purchaseSpecs = array();
                    //进货规格改为数组形式
                    $orderSpecs = explode(';',$order['specs_txt']);
                    foreach ($orderSpecs as $value){
                        if (!$value == ''){
                            $purchaseSpecs[] = $value;
                        }
                    }
                    foreach ($purchaseSpecs as $key => $value){
                        $str = substr($value,0,strrpos($value, "-"));
                        $list = explode('-',$str);
                        $newArr[$key]['specs'] =  $list;
                        //数量
                        preg_match_all("/\d+/",$value,$arr);
                        $newArr[$key]['number'] = $arr[0][0];
                    }
                    $purchaseSpecs = $newArr;
                    //修改商品规格库存
                    foreach ( $specs as $k => $v ){
                        foreach ( $purchaseSpecs as $kk => $vv ){
                            $result = array_diff($v['specs'],$vv['specs']);
                            if ( empty($result) ){
                                $specs[$k]['number'] = $v['number'] + $vv['number'];
                            }
                        }
                    }
                     //查询商品规格名
                     $specsName = GoodsSpecsName::where('goods_id',$goods['gid'])->get()->toArray();
                    //将商品规格数组还原为字符串形式
                    foreach ( $specs as $k => $v ){
                        $specsList = '';
                        for ( $i = 0;$i < count($v['specs']);$i++ ){
                            $specsList .= $specsName[$i]['name'].':'.$v['specs'][$i].';';
                    }
                    $specs[$k] = "[".$specsList."]--".$v['number'];
                }
                    $goods->specs_txt = implode('|',$specs);
                    $inventory = StoresCenterGoods::where(['goodsname' => $order['goods_name'],'stores_sn' => $stores_num])->value('inventory');
                    if ($inventory != $inventoryBefore ){
                        DB::rollback();
                        return ['code' => 0,'data' => '系统繁忙,请稍后再试'];
                    }
                    $inventoryAfter = $goods->inventory = $goods->inventory + $order['total_quantity'];
                    $re = $goods->save();
                    if (!$re) {
                        DB::rollback();
                        return ['code' => 0,'data' => '进货失败'];
                }
            }
                //增加库存修改记录
                if ( $inventoryBefore != $inventoryAfter ){
                    $storeGoodsData['store_number'] = $store['number'];
                    $storeGoodsData['store_name'] = $store['shop_name'];
                    $storeGoodsData['goods_name'] = $goods['goodsname'];
                    $storeGoodsData['goods_before'] = $inventoryBefore;
                    $storeGoodsData['goods_after'] = $inventoryAfter;
                    $storeGoodsData['resale_specs'] = $order['resale_specs'];
                    $storeGoodsData['purchase_specs'] = $order['specs_txt'];
                    $storeGoodsData['invoices_specs'] = $order['invoices_specs'];
                    $storeGoodsData['remark'] = '进货了'.$goods['goodsname'].',共'.$order['total_quantity'].'件';
                    $storeGoodsData['operator'] = '系统自动';
                    $storeGoodsData['addtime'] = time();
                    $storeGoodsSet = StoreGoodsSet::create($storeGoodsData);
                    if ( !$storeGoodsSet ){
                        DB::rollback();
                        return ['code' => 0,'data' => '进货失败'];
                }
            }

                    DB::commit();
                    return ['code' => 1,'data' => '已确认收货'];
                break;
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 补货入口
     */
    public function replenish()
    {
        return view('Home.stores.replenish');
    }

    public function getReplenish( Request $request ){
        $data = $request->all();
        $user = session('home_user');
        $StoresCenterModel = new StoresCenter();
        $StoresCenterGoodsModel = new StoresCenterGoods();
        $AddressModel = new Address();
        $membersModel = new Members();
        $GoodsModel = new ShopGoods();
        $storeGoodsAllId = [];
        $storeGoodsId = [];
        $stores_id = $StoresCenterModel->where(['uid'=>$user->uid])->value('id');
        $StoresNumber = $StoresCenterModel->where( [ 'id' => $stores_id ] )->value( 'number' );
        $store = $StoresCenterModel->where( [ 'id' => $stores_id ] )->first();
        $storeGoodsData = StoresCenterGoods::where( [ 'stores_id' => $stores_id ] )->select( 'gid' )->get()->toArray();
        foreach ($storeGoodsData as $key => $value) {
            array_push( $storeGoodsId, $value['gid'] );
        }
        $table = ShopGoodsClassify::where(['type'=>2])->select('id');
        $classify = $table->get()->toArray();
        $pid = [];
        if (!empty($classify)) {
            foreach ($classify as $value) {
                $pid[] = $value['id'];
            }
        } else {
            return ['code'=>0,'data'=>'暂时还没有商品'];
        }
        $goods = $GoodsModel->where( [ 'type' => 1, 'status' =>1 ] )->whereIn( 'cid', $pid )->select( 'id', 'goodsname' )->get()->toArray();
        foreach ($goods as $k => $v) {
            array_push( $storeGoodsAllId, [ 'gid' => $v['id'], 'goodsname' => $v['goodsname'] ] );
        }
        foreach ($storeGoodsAllId as $k => $v) {
            $goodsIdExist = in_array( $v['gid'], $storeGoodsId );
            if ( !$goodsIdExist ) {
                $goodsDatas['gid'] = $v['gid'];
                $goodsDatas['stores_id'] = $stores_id;
                $goodsDatas['stores_sn'] = $StoresNumber;
                $goodsDatas['goodsname'] = $v['goodsname'];
                $goodsDatas['inventory'] = 0;
                $goodsDatas['sold'] = 0;
                $goodsDatas['time'] = time();
                $goodsDatas['specs_txt'] = null;
                $storeGoodsDataAdd = $StoresCenterGoodsModel->insert( $goodsDatas );
            }
        }
        //获取门店信息
        $store = StoresCenter::where('uid',$user->uid)->first();
        switch ($data['class']){
            case 'select'://查询库存商品名称,总数及规格
                $storesId = $StoresCenterModel->where(['uid'=>$user->uid])->value('id');
                $goods = $StoresCenterGoodsModel->where(['stores_id'=>$storesId])->get()->toArray();
                if ( $goods ){
                    $arr = array();
                    foreach ( $goods as $key => $value ){
                        $price = ShopGoods::where('id',$value['gid'])->value('rulingprice');
                        $goods[$key]['price'] = $price;

                    }
                    //门店可补货金额
                    $invoices = StoresCenter::where('id',$storesId)->value('invoices');
                    return ['code' => 1,'data' =>$goods,'invoices' => $invoices];

                } else {
                    return ['code' => 0,'data' => '暂无数据'];
                }
                break;
            case 'add'://确认补货
                $ordersn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                //门店
                $address = $AddressModel->get_address($user->uid);
                if (!$address){
                    return ['code' => 0,'data' =>'请先添加收货地址'];
                }
                //获取门店商品库存
                $goodsData = StoresCenterGoods::where('stores_sn',$store['number'])->get()->toArray();

                //库存商品总价
                $totalPrice = 0;
                foreach ( $goodsData as $value ){
                    $univalence = ShopGoods::where('id',$value['gid'])->value('memberprice');
                    $goodsPrice = $univalence * $value['inventory'];
                    $totalPrice += $goodsPrice;
                }
                $goods = ShopGoods::where(['id' => $data['order']['gid']])->first();
                //补货商品数量
                $invoicesTotal = $data['order']['invoices'];

                if ($goods['rulingprice'] * $invoicesTotal > $store['invoices']){//如果复销补货商品价格大于售出复销订单价格
                    return ['code' => 0,'data' =>'补货商品价格不能超过已售订单价格'];
                }
                $order = [
                    'ordersn' => $ordersn,
                    'stores_num' => $store['number'],
                    'goods_id' => $data['order']['gid'],
                    'goods_name' => $goods['goodsname'],
                    'resale' => 0,
                    'invoices' => $invoicesTotal,
                    'stores_name' => $store['shop_name'],
                    'name' => $user->user_name,
                    'status' => 0,
                    'resale_specs' => '',
                    'invoices_specs' => '',
                    'created_at' => date('Y-m-d H:i:s',time())
                ];
                DB::beginTransaction();
                $res = Replenish::create($order);

                $orderId = Replenish::where(['ordersn' => $ordersn])->value('id');
                if ( $res ){
                    DB::commit();
                    return ['code' => 1,'data'=> $orderId ];
                } else {
                    DB::rollback();
                    return ['code' => 0,'data'=>'订单创建失败'];
                }
                break;
            case 'find'://查找订单
                //获取用户信息
                $member = $membersModel->find_members(['uid' => $user->uid],['credit1','credit2','credit3','credit4','credit5','voucher','level','stores_number']);
                //获取默认收货地址
                $address = $AddressModel->get_address($user->uid);
                if (!$address){
                    return ['code' => 0,'data' =>'请先添加收货地址'];
                }
                $order = Replenish::where(['id' => $data['id']])->first();
                $goods = ShopGoods::where(['id' => $order['goods_id']])->first();
                //根据收货地址计算运费
                $order->postage = 0;
                $order->save();
                //商品封面图
                $order['img'] = ShopGoods::where(['id' => $goods['id']])->value('goods_thumb');
                //订单总价(包含运费)
                $money = FIGURE( $member['credit1'],$member['credit2'],$order['postage']);
                $data = [
                    'order' => $order,
                    'address' => $address,
                    'money' => $money
                ];
                if ( $data ){
                    return ['code' => 1,'data' => $data];
                } else {
                    return ['code' => 0,'data' => '订单不存在'];
                }
                break;
            case 'pay':
                //获取门店信息
                $store = StoresCenter::where('uid',$user->uid)->first();
                $member = $membersModel->find_members(['uid' => $user->uid],['credit1','credit2','credit3','credit5','level','stores_number']);
                //获取收货地址
                $address = Address::where(['id' => $data['addressId']])->first();
                //获取订单
                $order = Replenish::where(['id'=>$data['id']])->first();
                //启动事务
                DB::beginTransaction();
                try{
                    //扣款
                    $money = [
                        'credit1' => $member->credit1 - $data['money']['data']['credit1'],
                        'credit2' => $member->credit2 - $data['money']['data']['credit2'],

                    ];
                    Members::where(['uid' => $user->uid])->update($money);
                    //修改订单状态
                    $order->address = $address['province'].$address['city'].$address['district'].$address['address'];
                    $order->consignee = $address['name'];
                    $order->phone = $address['phone'];
                    $order->status = 1;
                    $order->paytime = date('Y-m-d H:i:s',time());
                    $order->save();
                    //生成交易记录
                    $totalMoney = array_sum($data['money']['data']);
                    $transaction = [
                        'uid' => $user->uid,
                        'ordersn' => $order['ordersn'],
                        'money' => -$totalMoney,
                        'type' => 7,
                        'time' => time(),
                        'explain' => '门店补货',
                        'remark' => '电子币 : '.-$data['money']['data']['credit1'].' , 奖励币 : '.-$data['money']['data']['credit2']
                    ];
                    RecordTransaction::create($transaction);
                    //减少可补货金额
                    $goods = ShopGoods::where(['id' => $order['goods_id']])->first();
                    $store->invoices = $store->invoices - $order['invoices'] * $goods['rulingprice'] ;
                    if ($store->invoices < 0){
                        DB::rollback();
                        return ['code' => 0,'data' => '店铺补货余额不足'];
                    }
                    $rico = $store->save();
                    if (!$rico){
                        DB::rollback();
                        return[ 'code' => 0,'data' => '补货金额扣除失败'];
                    }
                    //提交事物
                    DB::commit();
                }catch (\Exception $exception){
                    //回滚
                    DB::rollBack();
                    return ['code' => 0 ,'data' =>'支付失败'];
                }
                return ['code' => 1 ,'data' =>'支付成功'];
                break;

        }

    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 补货记录
     */
    public function replenishRecord()
    {
        return view('Home.stores.replenishrecord');
    }

    public function getReplenishRecord( Request $request )
    {
        $data = $request->all();
        $user = session('home_user');
        switch ($data['class']){
            case 'select'://查询门店所有补货记录
                $stores_num = StoresCenter::where(['uid' => $user->uid])->value('number');//获取门店号
                $orders = Replenish::where(['is_cancel' => 1,'stores_num' => $stores_num])->orderBy('id','desc')->paginate(5);
                foreach ( $orders as $key => $value ){
                    $goods = ShopGoods::where(['id' => $value['goods_id']])->first();
                    $img = ShopGoods::where(['id' => $goods['id']])->value('goods_thumb');
                    $orders[$key]['img'] = $img;
                }
                if ( $orders ){
                    return ['code' => 1 ,'data' => $orders];
                } else {
                    return ['code' => 0 ,'data' => '暂无补货记录'];
                }
                break;
            case 'detail':
                $order = Replenish::where(['id' => $data['id']])->first();
                $goods = ShopGoods::where(['id' => $order['goods_id']])->first();
                //商品封面图
                $order['img'] = ShopGoods::where(['id' => $goods['id']])->value('goods_thumb');
                if ( $order ){
                    return ['code' => 1 ,'data' => $order];
                } else {
                    return ['code' => 0 ,'data' =>'参数错误'];
                }
                break;
            case 'confirm'://确认收货
                $order = Replenish::where(['id' => $data['id']])->first();
                $order->status = 3;
                $res = $order->save();
                if ( $res ){
                    return ['code' => 1,'data' => '已确认收货'];
                } else {
                    return ['code' => 0,'data' => '数据错误'];
                }
                break;
        }
    }

    /**
     * @param $weight
     * @param $province
     * @return float|int
     * 计算运费
     */

    public function getPostage( $weight ,$province )
    {
        $ares = ['辽宁省','吉林省','黑龙江省','甘肃省','青海省','宁夏回族自治区','海南省'];
        if ( $province == '西藏自治区') {
            if ( $weight > 1){
                $postage = 20 + ($weight-1) * 15;
            } else {
                $postage  = 20;
            }
        } else if ( $province == '内蒙古自治区'|| $province == '新疆维吾尔自治区'){
            if ( $weight > 1){
                $postage = 15 + ($weight-1) * 12;
            } else {
                $postage = 15;
            }
        } else if ( in_array($province,$ares)){
            if ( $weight > 2){
                $postage = 12 + ($weight-1) * 8;
            } else {
                $postage = 12;
            }
        } else {
            if ( $weight > 2){
                $postage = 6 + ($weight-1) * 4;
            } else {
                $postage = 6;
            }
        }
        return $postage;
    }

    
}